package com.javen.controller;

import com.alibaba.fastjson.JSONObject;
import com.javen.model.User;
import com.javen.service.IUserService;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Map;

@Controller
@RequestMapping({"/user"})
public class UserController {
    private static Logger log = LoggerFactory.getLogger(UserController.class);

    @Resource
    private IUserService userService;

    @RequestMapping(value = {"/login"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    @ResponseBody
    public JSONObject login(HttpServletRequest request, Model model) {
        JSONObject json = new JSONObject();
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        System.out.println(username + " " + password);
        User user = new User();
        if ((username != null) && (password != null)) {
            user.setUserName(username);
            user.setPassword(password);

            User user_find = new User();
            try {
                user_find = this.userService.getUserByUserName(username);
                System.out.println(user_find.getPassword());
                String vali_password = user_find.getPassword();
                if (password.equals(vali_password)) {
                    json.put("res", Integer.valueOf(1));
                    System.out.println("success");
                    log.debug(user.toString() + "Login success");
                    return json;
                }
                json.put("res", Integer.valueOf(0));
                log.debug(json.toJSONString() + "Login failed");
                return json;
            } catch (Exception e) {
                log.debug(e.toString());

                json.put("res", Integer.valueOf(0));
            }
        }
        return json;
    }


    @RequestMapping(value = {"/register"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    @ResponseBody
    public JSONObject register(HttpServletRequest request, Model model) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        JSONObject json = new JSONObject();

        User user = new User();
        user.setUserId("user_" + username);
        user.setUserName(username);
        user.setPassword(password);
        System.out.println(user);
        int res = this.userService.insert(user).intValue();
        if (res == 1) {
            json.put("res", Integer.valueOf(1));
        } else {
            json.put("res", Integer.valueOf(0));
        }
        return json;
    }


    @RequestMapping(value = {"/register_page"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET})
    public String registerPage(HttpServletRequest request, Model model) {
        return "demo_04_28/register_page";
    }


    @RequestMapping(value = {"/register_deal"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    public String registerDeal(HttpServletRequest request, Model model, HttpSession session) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String repassword = request.getParameter("repassword");
        String user_id = "user_" + username;
        User user = new User();
        user.setUserId(user_id);
        user.setUserName(username);
        user.setPassword(password);
        session.setAttribute("Current_user", user);
        ModelAndView mav = new ModelAndView("session");
        int res = this.userService.insert(user).intValue();
        System.out.println(res);
        return "demo_04_28/login";
    }

    @RequestMapping(value = {"/session/attributes"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET})
    public ModelAndView sessionAttributesage(HttpSession session) {
        User user = (User) session.getAttribute("Current_user");
        System.out.println(user.getUserName() + user.getPassword());
        ModelAndView mav = new ModelAndView("session");
        return mav;
    }

    @RequestMapping(value = {"/login"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET})
    public String loginPage(HttpServletRequest request, Model model) {
        return "demo_04_28/login";
    }

    @RequestMapping(value = {"/login_deal"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    public String loginDeal(HttpServletRequest request, Model model) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = new User();
        user = this.userService.getUserByUserName(username);
        String vali_pass = user.getPassword();
        if (vali_pass.equals(password)) {
            model.addAttribute("user", user);
            return "demo_04_28/login_success";
        }
        return "demo_04_28/login_failed";
    }

    @RequestMapping(value = {"/showuserid"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET})
    @ResponseBody
    public String showUserIdByUsername(HttpServletRequest request) {
        String username = request.getParameter("username");
        User user = new User();
        user = this.userService.getUserByUserName(username);
        String user_id = user.getUserId();
        return user_id;
    }


    @RequestMapping(value = {"/test"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET})
    public String test(HttpServletRequest request, Model model) {
        int userId = Integer.parseInt(request.getParameter("id"));
        System.out.println("userId:" + userId);
        User user = null;
        if (userId == 1) {
            user = new User();
            user.setId(Integer.valueOf(1));
            user.setPassword("123");
            user.setUserName("javen");
        }

        log.debug(user.toString());

        model.addAttribute("user", user);
        return "index";
    }

    @RequestMapping(value = {"/showUser"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET})
    @ResponseBody
    public User toIndex(HttpServletRequest request, Model model) {
        String username = request.getParameter("username");
        System.out.println("username:" + username);
        User user = this.userService.getUserByUserName(username);
        log.debug(user.toString());
        model.addAttribute("user", user);
        return user;
    }

    @RequestMapping(value = {"/showUser2"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET})
    public String toIndex2(@RequestParam("id") String id, Model model) {
        int userId = Integer.parseInt(id);
        System.out.println("userId:" + userId);
        User user = this.userService.getUserById(userId);
        log.debug(user.toString());
        model.addAttribute("user", user);
        return "showUser";
    }


    @RequestMapping(value = {"/showUser3/{id}"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET})
    public String toIndex3(@PathVariable("id") String id, Map<String, Object> model) {
        int userId = Integer.parseInt(id);
        System.out.println("userId:" + userId);
        User user = this.userService.getUserById(userId);
        log.debug(user.toString());
        model.put("user", user);
        return "showUser";
    }

    @RequestMapping(value = {"/{id}"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET})
    @ResponseBody
    public User getUserInJson(@PathVariable String id, Map<String, Object> model) {
        int userId = Integer.parseInt(id);
        System.out.println("userId:" + userId);
        User user = this.userService.getUserById(userId);
        log.info(user.toString());
        return user;
    }

    @RequestMapping(value = {"/jsontype/{id}"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET})
    public ResponseEntity<User> getUserInJson2(@PathVariable String id, Map<String, Object> model) {
        int userId = Integer.parseInt(id);
        System.out.println("userId:" + userId);
        User user = this.userService.getUserById(userId);
        log.info(user.toString());
        return new ResponseEntity(user, HttpStatus.OK);
    }

    @RequestMapping({"/upload"})
    public String showUploadPage() {
        return "user_admin/file";
    }

    @RequestMapping(value = {"/doUpload"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    public String doUploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            log.info("Process file:{}", file.getOriginalFilename());
        }
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File("E:\\", System.currentTimeMillis() + file.getOriginalFilename()));
        return "succes";
    }
}

